<!-- 库存盘点 -->
<template>
    <div >
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="showBack ? `${storehouse}-${zoneItem.name}-${classifyItem.cateName}-库存盘点` : '库存盘点'"
            @back="() => $router.go(-1)"
            :backIcon="showBack"
        >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="商品名称">
                            <a-input v-model="goodsName" allow-clear placeholder="请输入商品名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24" v-if="!showBack">
                        <a-form-item label="商品分类">
                            <a-select v-model="cateId" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item) in classifyList" :key="item.id" :value="item.id">{{item.cateName}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="商品信息">
                            <a-select show-search  v-model="goodsId" placeholder="请选择" @search="handleSearch" @change="getData">
                                <a-select-option v-for="(itm) in goodsList" :value="itm.goodsId+','+itm.id+','+itm.goodsName+','+itm.colorName+','+itm.grade+','+itm.specName+','+itm.remarks+','+itm.colorId+','+itm.specId" :key="itm.id"><span v-if="itm.isListed == '1'" style="color: red">(已上架)</span>{{itm.goodsName}}-{{itm.colorName}}-{{itm.grade}}-{{itm.specName}}-{{itm.remarks}}-{{itm.description}}</a-select-option>
                            </a-select> 
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24" v-if="!showBack">
                        <a-form-item label="仓库">
                            <a-select v-model="storehouseId" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item) in wareHouseList" :key="item.id" :value="item.id">{{item.storehouseName}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="getData()">查询</a-button>
                               <a-button style="margin-left: 20px" @click="_excelGoodsOrder()">导出</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table size="small" :columns="columns" :data-source="dataList" :loading="isload" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}">
            <div slot="goodsName" slot-scope="goodsName,record">
                <!-- <img v-if="imageUrl && imageUrl != ''" style="width: 100px;height: 50px" :src="imageUrl" alt="">
                <div v-else>-</div> -->
                <div class="flex alignCenter">
                    <!-- <img v-if="record.imageUrl && record.imageUrl != ''" style="width: 100px;height: 50px" :src="record.imageUrl" alt=""> -->
                    <a-avatar v-if="record.imageUrl && record.imageUrl != ''" :src="record.imageUrl" />
                    <div>{{goodsName}}</div>
                </div>
            </div>
            <div slot="imageUrl" slot-scope="imageUrl">
                <img v-if="imageUrl && imageUrl != ''" style="width: 100px;height: 50px" :src="imageUrl" alt="">
                <div v-else>-</div>
            </div>
            <div slot="storehouseId" slot-scope="storehouseId" > 
                <div v-for="(item,i) in wareHouseList" :key="i">
                    <a-tag v-if="item.storehouseId == storehouseId" :color="colors[i%13]">{{item.storehouseName}} </a-tag>
                </div>
            </div>
            <div slot="cateId" slot-scope="cateId">
                <div v-for="(item,i) in classifyList" :key="i">
                    <a-tag v-if="item.id == cateId" :color="colors[i%13]">{{item.cateName}} </a-tag>
                </div>
            </div>
            <div slot="stockQuantity" slot-scope="stockQuantity,record">
                <div class="flex alignCenter jusEnd">
                    <a-input v-if="updateId == record.id && upType == 'stockQuantity'" v-model="upValue" @pressEnter="pressEnter" />
                    <div v-else>{{stockQuantity}}</div>
                    <a-button type="link" @click="updateStock(record,'stockQuantity')"><a-icon type="edit" /></a-button>
                </div>
            </div>
            <div slot="triggerQuantity" slot-scope="triggerQuantity,record">
                <div class="flex alignCenter jusEnd">
                    <a-input v-if="updateId == record.id && upType == 'triggerQuantity'" v-model="upValue" @pressEnter="pressEnter"/>
                    <div v-else>{{triggerQuantity}}</div>
                    <a-button type="link" @click="updateStock(record,'triggerQuantity')"><a-icon type="edit" /></a-button>
                </div>
            </div>
            <div slot="replenishmentQuantity" slot-scope="replenishmentQuantity,record">
                <div class="flex alignCenter jusEnd">
                    <a-input v-if="updateId == record.id && upType == 'replenishmentQuantity'" v-model="upValue" @pressEnter="pressEnter"/>
                    <div v-else>{{replenishmentQuantity}}</div>
                    <a-button type="link" @click="updateStock(record,'replenishmentQuantity')"><a-icon type="edit" /></a-button>
                </div>
            </div>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="update(record)">修改</a-button>
                    <!-- <a-popconfirm
                        title="是否确认删除当前数据?"
                        ok-text="Yes"
                        cancel-text="No"
                        @confirm="del(record)"
                    >
                        <a-button class="errorColor" type="link">删除</a-button>
                    </a-popconfirm> -->
                </div>
            </template>
        </a-table>
        </a-page-header>

        <!-- 添加、修改商品库存盘点信息 -->
        <a-modal
            title="添加、修改商品库存盘点信息"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="库存备货量" >
                        <a-input v-model="item.stockQuantity" :placeholder="`请输入库存备货量`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="补货触发数量" >
                        <a-input v-model="item.triggerQuantity" :placeholder="`请输入补货触发数量`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="补货量" >
                        <a-input v-model="item.replenishmentQuantity" :placeholder="`请输入商品补货量`" allow-clear ></a-input>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { queryClassify } from '@/api/mall/classify';
import { queryGoodsDetail , queryGoodsStorehouseBindConfigByUserid , queryGoodsStockVerification , updateGoodsStockVerification , excelGoodsStockVerification } from '@/api/newMall';
import { columns } from './table';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            storehouse: JSON.parse(localStorage.getItem('storehouseName')),
            // storehouseId: JSON.parse(localStorage.getItem('storehouseId')),
            zoneItem: JSON.parse(localStorage.getItem('zoneItem')),
            classifyItem: JSON.parse(localStorage.getItem('classifyItem')),
            merchantId: sessionStorage.getItem('merchantId') ?? '0',
            userId: sessionStorage.getItem('userId'),
            // cateId: localStorage.getItem('classifyItem') ? JSON.parse(localStorage.getItem('classifyItem')).id : undefined,
            cateId: undefined,
            classifyList: [], // 分类列表
            goodsName: '', // 商品名称
            goodsId: undefined, // 商品id
            goodsList: [], // 商品筛选列表
            storehouseId: undefined, // 仓库id
            wareHouseList: [], // 仓库列表
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            page: 1,
            size: 10,
            total: 0,
            dataList: [],
            isload: false,
            confirmLoading: false,
            columns,
            updateId: '',
            upType: '',
            upValue: '',
            item: {
                id: '',
                stockQuantity: '', // 库存备货量
                triggerQuantity: '', // 补货触发数量
                replenishmentQuantity: '', // 补货量
            },
            visible: false,
            confirmLoading: false,
            showBack: false,
        };
    },
    async created(){
        try {
            if(this.$route.query.isClassify == '1'){
                this.showBack = true;
                this.storehouseId = JSON.parse(localStorage.getItem('storehouseId'));
                this.cateId = JSON.parse(localStorage.getItem('classifyItem')).id;
            }else{
                this.storehouseId = undefined;
                this.cateId = undefined;
                await this.getClassify();
                await this._queryAllHouse();
            }
            await this.getGoods();
            this.getData();
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        async handleSearch(goodsName){
            console.log(goodsName,'name')
            await this.getGoods(goodsName);
        },
        // 获取商品选择列表
        getGoods(selGoodsName,goodsDetailId){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId': _this.brandId,
                    'id': goodsDetailId,
                    'cateId': _this.cateId,
                    'storehouseId': _this.storehouseId,
                    // 'areaId': ,
                    'goodsName': selGoodsName,
                    'status': '1',
                    'page': 0,
                    'size': 99,
                }
                queryGoodsDetail(params)
                .then(res => {
                    if(res.success){
                        if(!goodsDetailId){
                            _this.goodsList = res.data.content;
                        }
                        resolve(res.data.content);
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 获取分类信息
        async getClassify(){
            let _this = this;
            try {
                const params = {
                    'brandId':_this.brandId,
                    // 'parentId':'0',
                    'level': '2',
                    'size': 99,
                    'page': 0,
                }
                _this.classifyList = await _this._queryClassify(params);
            } catch (error) {
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
        },
        _queryClassify(params,type){
            var _this=this
            return new Promise((resolve,reject) => {
                queryClassify(params)
                .then(res=>{
                    if(res.success){
                        resolve(res.data.content)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 查询所有仓库
        _queryAllHouse(){
            let _this = this;
            return new Promise((resolve,reject) => {
                queryGoodsStorehouseBindConfigByUserid({
                    'brandId': _this.brandId,
                    'userId': _this.userId,
                })
                .then(res => {
                    if(res.success){
                        _this.wareHouseList = res.data;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 获取商品库存信息
        getData(){
            let _this = this;
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'cateId': _this.cateId,
                'goodsName': _this.goodsName,
                'goodsId': _this.goodsId,
                'merchantId': _this.merchantId,
                'page': _this.page - 1,
                'size': _this.size,
            }
            _this.isload = true;
            queryGoodsStockVerification(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data.content;
                    _this.total = res.data.totalElements
                    console.log(_this.dataList,'datalIST')
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(){
            this.item.id = ''
            this.item.stockQuantity = '';
            this.item.triggerQuantity = '';
            this.item.replenishmentQuantity = '';
            this.visible = true;
        },
        // 修改
        update(item){
            this.item = JSON.parse(JSON.stringify(item))
            this.visible = true;
        },
        // 确定添加、修改
        handleOk(){
            let _this = this
            _this.confirmLoading = true
            _this.confirmLoading = true;
            const params = {
                'id': _this.item.id,
                'stockQuantity': _this.item.stockQuantity,
                'triggerQuantity': _this.item.triggerQuantity,
                'replenishmentQuantity': _this.item.replenishmentQuantity,
            }
            updateGoodsStockVerification(params)
            .then(res=>{
                _this.confirmLoading = false
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '修改成功',
                        duration: 8,
                    })
                    _this.visible = false
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除
        del(item){
            let _this = this;
            const params = {
                'id': item.id,
                'isDelete': '1'
            }
            updateGoodsStockVerification(params)
            .then(res => {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 修改单个数据
        updateStock(item,type){
            this.upType = type;
            this.updateId = item.id;
            this.upValue = item[type];
            console.log(this.upType,this.updateId,'type,id')
            // this.item = JSON.parse(JSON.stringify(item))
        },
        pressEnter(){
            let _this = this;
            var type = _this.upType;
            const params = {
                'id': _this.updateId,
            }
            params[type] = _this.upValue;
            updateGoodsStockVerification(params)
            .then(res=>{
                _this.confirmLoading = false
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '修改成功',
                        duration: 8,
                    })
                    _this.upType = '';
                    _this.updateId = '';
                    _this.upValue = '';
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        _excelGoodsOrder(){
            let _this = this
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'cateId': _this.cateId,
                'goodsName': _this.goodsName,
                'goodsId': _this.goodsId,
                'merchantId': _this.merchantId,
                'page': _this.page - 1,
                'size': _this.size,
                'gtVacancyQuantity': '0',
                'isExportExcel':1,
                'size': _this.total ?? 9999,
            }
            excelGoodsStockVerification(params)
            .then(res=>{
                if(res){
                      const content = res
                      console.log(res,"res")
                        const blob = new Blob([content])
                        const fileName = '商品补货列表.xlsx'
                        if ('download' in document.createElement('a')) { // 非IE下载
                        const elink = document.createElement('a')
                        elink.download = fileName
                        elink.style.display = 'none'
                        elink.href = URL.createObjectURL(blob)
                        document.body.appendChild(elink)
                        elink.click()
                        URL.revokeObjectURL(elink.href) // 释放URL 对象
                        document.body.removeChild(elink)
                        } else { // IE10+下载
                        navigator.msSaveBlob(blob, fileName)
                        }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
    }
}

</script>
<style scoped>

</style>